package com.zd.zjfx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

public class ZipUtil {

	/**
	 * 解压到指定目录
	 */
	public static void unZipFiles(String zipPath, String descDir) throws IOException {
		unZipFiles(new File(zipPath), descDir);
	}

	/**
	 * 解压文件到指定目录
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(File zipFile, String descDir) throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		// 解决zip文件中有中文目录或者中文文件
		ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			;
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
			unziprar(descDir);
		}
	}

	
	public static void main(String[] args) throws IOException {
		/**
		 * 解压文件
		 */
		Date a=new Date();
		//File zipFile = new File("d:/1300922920200612092847.zip");
		//String path = "d:/zipfile/";
		String f = "F:\\132新\\";
		unziprar(f);
		Date b=new Date();
		System.out.println(a);
		System.out.println(b);
	}
	
	public static String unziprar(String basepath) throws IOException {
		File file = new File(basepath);
		String[] test = file.list();
		for (int i = 0; i < test.length; i++) {
			System.out.println(test[i]);
			if (test[i].toLowerCase().endsWith(".zip")) {
				String filepath=basepath+test[i];
				System.out.println(filepath);
				String savepath = filepath.substring(0, filepath.lastIndexOf(".")) + File.separator;
				unZipFiles(filepath, savepath);
	        }else if(test[i].toLowerCase().endsWith(".rar")){
	        	String filepath=basepath+test[i];
				String savepath = filepath.substring(0, filepath.lastIndexOf(".")) + File.separator;
	        	unrar(filepath, savepath);
	        }
			
		}
		return basepath;
		
		
		
	}
	
	/**
     * 根据原始rar路径，解压到指定文件夹下.
     *
     * @param srcRarPath       原始rar路径
     * @param dstDirectoryPath 解压到的文件夹
     */
    public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
        if (!srcRarPath.toLowerCase().endsWith(".rar")) {
            System.out.println("非rar文件！");
            return;
        }
        File dstDiretory = new File(dstDirectoryPath);
        if (!dstDiretory.exists()) {// 目标目录不存在时，创建该文件夹
            dstDiretory.mkdirs();
        }
        Archive a = null;
        File srcrar=new File(srcRarPath);
        try {
        	InputStream in = new FileInputStream(srcrar);
            a = new Archive(in);
            if (a != null) {
                a.getMainHeader().print(); // 打印文件信息.
                FileHeader fh = a.nextFileHeader();
                while (fh != null) {
                    if (fh.isDirectory()) { // 文件夹
                        File fol = new File(dstDirectoryPath + File.separator
                                + fh.getFileNameString());
                        fol.mkdirs();
                    } else { // 文件
                        File out = new File(dstDirectoryPath + File.separator
                                + fh.getFileNameString().trim());
                        try {// 之所以这么写try，是因为万一这里面有了异常，不影响继续解压.
                            if (!out.exists()) {
                                if (!out.getParentFile().exists()) {// 相对路径可能多级，可能需要创建父目录.
                                    out.getParentFile().mkdirs();
                                }
                                out.createNewFile();
                            }
                            FileOutputStream os = new FileOutputStream(out);
                            a.extractFile(fh, os);
                            os.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    fh = a.nextFileHeader();
                }
                in.close();
                a.close();
                unziprar(dstDirectoryPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static final String winrarPath = "C:/Program Files/WinRAR/WinRAR.exe"; 
    public static boolean unrar(String rarFile, String target) {     
        boolean bool = false;     
        File f=new File(rarFile);  
        if(!f.exists()){  
            return false;  
        }  
        String cmd = winrarPath + " X " + rarFile + " "+target;    
        try {     
            Process proc = Runtime.getRuntime().exec(cmd);     
            if (proc.waitFor() != 0) {     
                if (proc.exitValue() == 0) {     
                    bool = false;     
                }     
            } else {     
                bool = true;     
            }
            unziprar(target);
        } catch (Exception e) {     
            e.printStackTrace();     
        }     
        return bool;     
    }
    
}
